package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.UserLocation;
import com.itheima.service.mongo.UserLocationService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;

import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserLocationServiceImpl implements UserLocationService {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存或者更新地址
    @Override
    public void saveOrUpdateUserLocation(Double latitude, Double longitude, String addrStr, Long userId) {
        //1.查询该用户的地址是否存在
        Query query = new Query(
                Criteria.where("userId").is(userId)
        );
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        if (userLocation == null) {
            //2.如果不存在 保存
            userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setAddress(addrStr);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(System.currentTimeMillis());
            userLocation.setLastUpdated(System.currentTimeMillis());
            //坐标
            GeoJsonPoint geoJsonPoint = new GeoJsonPoint(longitude, latitude); //是app 传入反了
            userLocation.setLocation(geoJsonPoint);
            mongoTemplate.save(userLocation);
        } else {
            //3.如果存在 更新
            userLocation.setAddress(addrStr);
            userLocation.setLastUpdated(userLocation.getUpdated());//将上一次的时间保存一下
            userLocation.setUpdated(System.currentTimeMillis()); //更新当前时间
            //坐标
            GeoJsonPoint geoJsonPoint = new GeoJsonPoint(longitude, latitude);
            userLocation.setLocation(geoJsonPoint);
            mongoTemplate.save(userLocation); //就是save
        }
    }

    /**
     * 根据当前用户对象 和 半径搜索好友
     *
     * @param loginUserId
     * @param distance
     * @return
     */
    @Override
    public List<Long> searchUser(Long loginUserId, String distance) {
        //先查原来的位置
        Query query = new Query(
                Criteria.where("userId").is(loginUserId)
        );
        //当前的用户位置
        UserLocation curUserLocation = mongoTemplate.findOne(query, UserLocation.class);

        //1. 确定圆心
        //GeoJsonPoint location = curUserLocation.getLocation();

        //2. 确定半径 KILOMETERS 千米 单位
        Distance dis = new Distance(Double.valueOf(distance) / 1000, Metrics.KILOMETERS);
        //3. 画个圆圈
        Circle circle = new Circle(curUserLocation.getLocation(), dis);
        //4. 圆中查找
        Query query2 = new Query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocationList = mongoTemplate.find(query2, UserLocation.class);

        List<Long> ids = new ArrayList<>();
        //将遍历的每一个对象id进行存储返回
        if (CollectionUtil.isNotEmpty(userLocationList)) {
            for (UserLocation userLocation : userLocationList) {
                ids.add(userLocation.getUserId());
            }
        }
        return ids;
    }

    /**
     * 根据用户ID查询用户位置信息
     */
    @Override
    public Map<String, String> findUserLocation(Long UserId) {
        Query query_userLocation = new Query(
                Criteria.where("userId").is(UserId)
        );
        UserLocation userLocation = mongoTemplate.findOne(query_userLocation, UserLocation.class);

        GeoJsonPoint location = null;
        if (userLocation != null) {
            location = userLocation.getLocation();
        }
        if (userLocation == null){
            location = new GeoJsonPoint(116.635564,40.169357);
        }

        Map<String, String> map = new HashMap<>();
        map.put("longitude", String.valueOf(location.getX()));
        map.put("latitude", String.valueOf(location.getY()));

        return map;
    }
}
